package Controller;

import entity.Admin;
import entity.Book;
import entity.Borrow;
import entity.Reader;
import service.BookService;
import service.LoginService;
import service.impl.BookServiceImpl;
import service.impl.LoginServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private LoginService loginService=new LoginServiceImpl();

    Reader reader=null;
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String username=req.getParameter("username");
        String password=req.getParameter("password");
        String type = req.getParameter("type");
        Object object= null;
        try {
            object = loginService.login(username,password,type);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (object!=null){
            HttpSession session=req.getSession();
            switch (type){
                case "reader":
                    Reader reader= (Reader) object;
                    session.setAttribute("reader",reader);
                    resp.sendRedirect("/book?page=1");
                    break;
                case "admin":
                    Admin admin=(Admin)object;
                    session.setAttribute("admin",admin);
                    resp.sendRedirect("/admin?method=findAllBorrow&page=1");
                    /*try {
                        resp.sendRedirect("/admin?method=findAllBorrow&page=1");
                        List<Borrow> borrowList=bookService.findAllBorrowByState(0,1);
                        System.out.println(borrowList);
                        req.setAttribute("list",borrowList);
                        req.getRequestDispatcher("admin.jsp").forward(req,resp);
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }*/
                    break;
            }
        }
        else {
            resp.sendRedirect("login.jsp");
        }
    }
}
